package datas

import (
	"errors"
	"io/ioutil"
	"math/rand"
	"strconv"
	"strings"
)

type Rule string

func (mem *Mem) LoadServers(ru string) {
	buf, err := ioutil.ReadFile(ru)
	if err != nil {
		return
	}
	servers, ok := mem.Kd["Routes"]
	if !ok {
		mem.Kd["Routes"] = make(Gi)
		servers, _ = mem.Kd["Routes"]
	}
	for _, l := range strings.Split(string(buf), "\n") {
		if strings.Contains(l, ":") {
			servers[strings.TrimSpace(l)] = true
		}
	}
	return
}

func (mem *Mem) RouteRandom(routeCmd string) (routeS string, err error) {
	if strings.Count(routeCmd, "-") == 2 {
		ss := strings.SplitN(routeCmd, "-", 3)
		num, eerr := strconv.Atoi(ss[1])
		if eerr != nil {
			err = eerr
			return
		}
		Start := ss[0]
		End := ss[1]
		routeS = Start
		Used := 0
		if servers, ok := mem.Kd["Routes"]; ok {
			if _, ok = servers[Start]; ok {
				if _, ok = servers[End]; ok {
					for {
						if Used == num {
							break
						}
						for s := range servers {
							if Used == num {
								break
							}
							if s != Start && s != End && Used < num {
								if rand.Float32() > 0.5 {
									routeS += "-" + s
									Used++
								}
							}
						}
					}
					routeS += "-" + End
				} else {
					err = errors.New("End can not be found in Mem!")
				}
			} else {
				err = errors.New("Start can not be found in Mem!")
			}
		} else {
			err = errors.New("no server can be found in Mem!")
		}
	}
	return
}
